package com.thd.springboottest.jackson.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.thd.springboottest.jackson.bean.CommonBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * com.thd.springboottest.jackson.util.JacksonUtil
 *
 * @author: wanglei62
 * @DATE: 2020/3/31 8:21
 **/
public class JacksonUtil {
    private static Logger log = LoggerFactory.getLogger(JacksonUtil.class);
    private static ObjectMapper objectMapper = new ObjectMapper();



    static {
        //该属性设置主要是将对象的排除空值属性，若有特殊需求，可以进入JsonSerialize.Inclusion该枚举类查看
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        // null属性也会序列化
//        objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);

        //该属性设置主要是取消将对象的时间默认转换timesstamps(时间戳)形式
//        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

        //该属性设置主要是将忽略空bean转json错误
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);

        //忽略在json字符串中存在，在java类中不存在字段，防止错误。
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        //所有日期都统一为以下样式：yyyy-MM-dd HH:mm:ss，这里可以不用我的DateTimeUtil.DATE_FORMAT，手动添加
//        objectMapper.setDateFormat(new SimpleDateFormat(DateTimeUtil.DATE_FORMAT));

        // 处理LocalDateTime localDate localTime类型的属性
        JavaTimeModule timeModule = new JavaTimeModule();
        objectMapper.registerModule(timeModule);
    }

    /**
     * 封装序列化方法
     * @param obj
     * @param <T>
     * @return
     */
    public static <T> String objToJson(T obj) {
        if (obj == null) {
            return null;
        }

        try {
            return obj instanceof String ? (String)obj : objectMapper.writeValueAsString(obj);
        } catch (Exception e) {
            log.warn("obj To json is error", e);
            return null;
        }
    }
    /**
     *  封装反序列化方法
     */
    public static <T> T json2Object(String json, Class<T> clazz) {
        if (StringUtils.isEmpty(json) || clazz == null) {
            return null;
        }

        try {
            return clazz.equals(String.class) ? (T)json : objectMapper.readValue(json, clazz);
        } catch (Exception e) {
            log.warn("json To obj is error", e);
            return null;
        }
    }

    public static JsonNode json2JsonNode(String json){
        try {
            return objectMapper.readTree(json);
        } catch (Exception var2) {
            var2.printStackTrace();
            return null;
        }
    }


    public static void main(String[] args) throws Exception{
        CommonBean cb = new CommonBean();
        cb.setAge(5);
        cb.setBalance(new BigDecimal(25.222321));
        cb.setBir(new Date());
        cb.setName("devil13th");
        cb.setLocalDate(LocalDate.now());
        cb.setLocalDateTime(LocalDateTime.of(2020,10,20,23,22,21));
        cb.setCreateTime(new Date());

        String json = objectMapper.writeValueAsString(cb);
        System.out.println(json);


        String jsonStr = "{\"age\":5,\"balance\":25.22232100000000087902662926353514194488525390625,\"localDateTime\":\"2020-10-20 23:22:21\",\"localDate\":\"2022-08-11\",\"bir\":\"2022-08-11\",\"createTime\":\"2022-08-11 09:38:36\"}";
        CommonBean commonBean = objectMapper.readValue(jsonStr,CommonBean.class);
        System.out.println(commonBean);

    }
}
